package cn.lyf.myblog.controller.view;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;

import javax.servlet.http.HttpSession;
import java.util.*;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.lyf.myblog.mybatis.mappers.UserInfo2Mapper;

@Controller
public class Login {
    @Autowired
    UserInfo2Mapper userInfo2Mapper;

    @RequestMapping(value = "/toLogin")
    public String login() throws Exception {
        return "/toLogin";
    }

    @RequestMapping(value = "/register")
    public String register() throws Exception {
        return "/register";
    }

    @PostMapping("/login")
    public String login(String username, String password, HttpSession session, Model model) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        try {
            subject.login(token);
        } catch (UnknownAccountException e1) {
            model.addAttribute("msg", "用户不存在");
            return "/toLogin";
        } catch (IncorrectCredentialsException e2) {
            model.addAttribute("msg", "密码错误");
            return "/toLogin";
        }
        Integer uid = (Integer) subject.getSession().getAttribute("uid");
        session.setAttribute("username", subject.getSession().getAttribute("username"));
        session.setAttribute("uid", uid);
        Map<String, Object> map = userInfo2Mapper.selectUserInfo2ById(uid);
        session.setAttribute("avatar", map.get("avatar"));
        session.setAttribute("brief", map.get("brief"));
        return "/user/index";
    }

}
